package autohome.wz.lib;

import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;

import java.io.UnsupportedEncodingException;

/**
 * Created with Administrator
 * DATE:2017/2/15
 * Time:10:23
 */
public class RText {


    /**
     * 对中文字符串进行编码，防止乱码
     *
     * @param plainText 传入字符串
     * @return 返回编码后的结果
     */
    public static String encodeURL(String plainText) {
        String value;
        try {
            value = new String(plainText.getBytes("iso-8859-1"), "gb2312");
        } catch (UnsupportedEncodingException e) {
            value = "";
        }
        return value;
    }

    /**
     * 对中文字符编码，防止乱码
     *
     * @param plainText 传入字符串
     * @return 返回编码后的结果
     */
    public static String encodeURLToUTF8(String plainText) {
        if (isEmpty(plainText)) {
            return null;
        }
        String value;
        try {
            value = new String(plainText.getBytes("iso-8859-1"), "utf-8");
        } catch (UnsupportedEncodingException e) {
            value = "";
        }
        return value;
    }


    private static boolean isEmpty(Object obj) {
        return StringUtils.isEmpty(ObjectUtils.toString(obj))
                || ObjectUtils.toString(obj).equals("undefined");
    }


    public static String chinaToUnicode(String str) {
        String result = "";
        for (int i = 0; i < str.length(); i++) {
            int chr1 = str.charAt(i);
            if (chr1 >= 19968 && chr1 <= 171941) {// 汉字范围 \u4e00-\u9fa5 (中文)
                result += "\\u" + Integer.toHexString(chr1);
            } else {
                result += str.charAt(i);
            }
        }
        return result;
    }


    /**
     * 将iso8859-1转为utf-8
     *
     * @param plainText 原始字符串
     * @param t         t为true发生异常时返回原始字符串否则返回空串
     * @return
     */
    public static String encodeURLToUTF8KT(String plainText, boolean t) {
        String value = null;
        if (StringUtils.isEmpty(plainText)) {
            return "";
        }
        try {
            value = new String(plainText.getBytes("iso-8859-1"), "utf-8");
        } catch (UnsupportedEncodingException e) {
            if (t) {
                value = plainText;
            } else {
                value = "";
            }
        }
        return value;
    }


}
